package net.kong.sns.rest.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import net.kong.sns.rest.client.rest.RestClient;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mortbay.jetty.Handler;
import org.mortbay.jetty.Request;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.handler.AbstractHandler;

/**
 * @author yk
 * @version $Id: ClientTestBase.java,v 1.4.2.1 2009/12/21 09:38:30 wangyuanming Exp $
 */
public class ClientTestBase {
    private static Log log=LogFactory.getLog(ClientTestBase.class);
    private static Server restServer;
    protected static Client client = null;
    protected static Client client_noSessionKey = null;
    private static int port = 10068;
    private Reader response_reader;
    static JAXBContext jc;
    static Unmarshaller um;
    protected Map parameterMap;
    protected static String apiKey="for-test-apiKey";
    protected static String apiSecret="for-test-apiSecret";
    protected static String sessionkey="for-test-sessionkey";
    
    static {
        RestClient.REST_BASE_URI = String.format("http://localhost:%s/service", port);
        try {
            System.setProperty("apiKey", apiKey);
            System.setProperty("apiSecret", apiSecret);
            client = ClientFactory.createInstance(sessionkey);
            client_noSessionKey=ClientFactory.createInstance();
        }
        catch (IOException e1) {
            e1.printStackTrace();
        }
        restServer = new Server(port);
        try {
            restServer.start();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        try {
            jc = JAXBContext.newInstance(ClientTestBase.class.getPackage().getName());

            um = jc.createUnmarshaller();
//            um.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    public ClientTestBase(InputStream in) {
        try {
            this.response_reader = new InputStreamReader(in, "UTF-8");
        }
        catch (UnsupportedEncodingException e) {
        }
        Handler restHandler = new RestServerHandler();
        restServer.setHandler(restHandler);
    }
    public ClientTestBase(Reader response_reader) {
        this.response_reader =response_reader;
        Handler restHandler = new RestServerHandler();
        restServer.setHandler(restHandler);
    }

    private class RestServerHandler extends AbstractHandler {

        public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException,
                ServletException {
            parameterMap=request.getParameterMap();
            JsonMockData jsonData =null;
            try {
                jsonData = (JsonMockData) ((javax.xml.bind.JAXBElement) um.unmarshal(response_reader)).getValue();
            }
            catch (JAXBException e) {
                e.printStackTrace();
            }
            String headers= jsonData.getHead();
            if(StringUtils.isNotEmpty(headers)){
                for(String aheader:headers.split("\n")){
                    String[] entry=aheader.split("=");
                    response.addHeader(entry[0], entry[1]);
                }
            }
            response.setContentType("application/json");
            response.getWriter().print(jsonData.getBody());
            String uri = request.getRequestURI();
            log.info(String.format("hander url:=%s", uri));
            ((Request) request).setHandled(true);
        }
    }
}
